import config from '../config/index.js'
import utils from '../utils/util.js'
const app = getApp();
let lock = false;
let job = [];

const _login = (cb) => {
  // return new Promise((resolve, reject) => {
  let code = '';
  wx.pro.login().then(res => {
    console.log(res)
    code = res.code;
    return wx.pro.getSetting()
  }).then(res => {
    if (res.authSetting['scope.userInfo']) {
      return wx.pro.getUserInfo()
    }
  }).then(res => {
    return postRequest('/zp/api/wx_login', {
      code: code,
      iv: res.iv,
      encryptedData: res.encryptedData,
      userinfo: JSON.stringify(res.userInfo)
    })
  }).then(res => {
    let token = res.data.token;
    let userInfo = res.data.userinfo
    wx.setStorageSync('t', token)
    wx.setStorageSync('userInfo', userInfo)
    // console.log('登陆成功', userInfo)
    app.globalData.userInfo = userInfo;
    cb && cb(res);
   
  }).catch(error => {
    // console.log(error)
  })
}

function wxPromisefy(obj = {}) {
  return new Promise((resolve, reject) => {
    obj.header = obj.header ? obj.header : {}
    obj.header = Object.assign(obj.header, {
      'token': wx.getStorageSync('t')
    })
    obj.success = function (res) {
      //console.log('success res: ', res);
      // 未登录或token 过期， 重新调用登陆接口 
      if (res.data.code == 3) {
        //console.log('未登录')
        job.push({
          url: obj.url,
          method: obj.method,
          header: utils.deepClone(obj.header),
          data: JSON.parse(JSON.stringify(obj.data || {})),
          success: obj.success,
          fail: obj.fail,
        });
        if (!lock) {
          _login(data => {
            lock = false;
            for (let i = 0; i < job.length; i++) {
              console.log('重新发送请求', job[i])
              job[i].header.token = data.data.token;
              wx.request({
                ...job[i]
              });
            };
            job = [];
          })
        }
        return;
      }
      resolve(res.data)
    }
    wx.request(obj);
  })
}

function postRequest(url, data = {}, header = {}) {
  return wxPromisefy({
    url: config.domain + url,
    method: 'POST',
    data: data,
  })
}

function getRequest(url, data = {}, header = {}) {
  return wxPromisefy({
    url: config.domain + url,
    method: 'POST',
    data: data
  })
}
function bindGetUserInfo(res) {
  let data = res.detail;
  if (data.errMsg == 'getUserInfo:ok') {
    let userInfo = res.detail.userInfo;
    let iv = res.detail.iv;
    let encryptedData = res.detail.encryptedData;
    alogin(userInfo, iv, encryptedData)
  }
}

function alogin(userInfo, iv, encryptedData) {
  wx.login({
    success: data => {
      let code = data.code;
      getRequest('/zp/api/wx_login', {
        userinfo: JSON.stringify(userInfo),
        iv,
        encryptedData,
        code: code
      }).then(res => {
        let token = res.data.token;
        let userInfo = res.data.userinfo;
        let audits = res.data.audit ? res.data.audit : 1;
        wx.setStorageSync('t', token)
        wx.setStorageSync('userInfo', userInfo)
        wx.setStorageSync('isFirst', userInfo);
        app.globalData.userInfo = userInfo;
        app.globalData.userToken = token;
        wx.showToast({
          title: res.message,
          icon: res.code=='0'?'success':'none'
        })
        app.userInfoReadyCallback({
          userInfo: userInfo
        })
      }).catch(error => {
        if (error.code) {
          wx.showToast({
            title: error.message,
            icon: 'none'
          })

        } else {
          wx.showToast({
            title: '授权失败',
            icon: 'none'
          })
        }

      })
    }
  })
}

module.exports = {
  postRequest: postRequest,
  getRequest: getRequest,
  bindGetUserInfo: bindGetUserInfo
}